package com.lb.shopguide.ui.fragment.guide.recommend;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebSettings;
import android.widget.TextView;

import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.DefaultHandler;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.base.BaseFragment;
import com.lb.shopguide.config.AppConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.recommend.RecBannerBean;
import com.lb.shopguide.entity.recommend.RecommendDetailGoodsBean;
import com.lb.shopguide.entity.recommend.RecommendGoodsBean;
import com.lb.shopguide.entity.trace.TraceBean;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.shopguide.trace.TraceManager;
import com.lb.shopguide.ui.activity.ActivityActivityDetail;
import com.lb.shopguide.ui.dialog.DialogShare2Wechat;
import com.lb.shopguide.ui.view.NormalTitleBar;
import com.lb.shopguide.ui.view.slidedetail.SlideDetailsLayout;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.AdJumpUtil;
import com.lb.shopguide.util.lb.BizUtil;
import com.trello.rxlifecycle2.android.FragmentEvent;

import butterknife.BindView;

/**
 * Create by kangzhao on 2018/12/1
 */
public class FragmentRecGoodsDetail extends BaseCommonFragment {
    @BindView(R.id.ntb)
    NormalTitleBar ntb;
    @BindView(R.id.slide_layout)
    SlideDetailsLayout mSlideDetailsLayout;
    @BindView(R.id.webview)
    BridgeWebView mWebview;
    @BindView(R.id.tv_goods_status)
    TextView tvGoodsStatus;

    private String shareUrl;

    private boolean shareFlag = false;


    private RecommendDetailGoodsBean recommendDetailGoodsBean;

    public static FragmentRecGoodsDetail newInstance(String productCode) {
        FragmentRecGoodsDetail fragmentRecGoodsDetail = new FragmentRecGoodsDetail();
        Bundle bundle = new Bundle();
        bundle.putSerializable(AppConstant.PRODUCT_CODE, productCode);
        fragmentRecGoodsDetail.setArguments(bundle);
        return fragmentRecGoodsDetail;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_rec_goods_detail;
    }

    @Override
    public void initData() {
        Bundle bundle = getArguments();
        String product = "";
        if (bundle.containsKey(AppConstant.PRODUCT_CODE)) {
            product = bundle.getString(AppConstant.PRODUCT_CODE);
        }
        if (!TextUtils.isEmpty(product)) {
            getRecommendGoodsDetail(product);
            getProductDetailPic(product);
        }
    }

    @Override
    public void initView() {
        ntb.setLeftImageSrc(R.drawable.iv_back);
        ntb.setTitleText("商品详情");
        ntb.setOnLeftImageListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
            }
        });
        tvGoodsStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (shareFlag) {
                    shareLogic();
                }
            }
        });

        WebSettings webSettings = mWebview.getSettings();
        webSettings.setBuiltInZoomControls(false);
        webSettings.setUseWideViewPort(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportMultipleWindows(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setLightTouchEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setTextSize(WebSettings.TextSize.NORMAL);
//        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebview.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebview.setDefaultHandler(new DefaultHandler());
    }

    public void shareLogic() {
        int orderEntranceCode = -1;
        int productType = -1;
        if (recommendDetailGoodsBean.isSecSymbol()) {
            orderEntranceCode = AppConstant.RECOMMEND_GOODS;
            productType = AppConstant.PTYPE_RECOMMEND_GOODS;
        } else {
            orderEntranceCode = AppConstant.COMMON_GOODS;
            productType = AppConstant.PTYPE_COMMON_GOODS;
        }
        if (AppConfigManager.getAppconfigManager(mContext).getDevMode() == AppConstant.KEY_RUN_MODE_FORMAL) {
            shareUrl = "https://singlepage.storeer.com/activity_2018/eightHalf_index?productCode=" + recommendDetailGoodsBean.getProductCode() + "&appEntranceType=" +
                    AppConstant.APP_ENTRANCE_ANDROID + "&linkStaffCode=" + mUserConfigManager.getUserId() + "&xd_code=XD0001" + "&orderEntryCode=" + orderEntranceCode + "&productType=" + productType;
        } else {
            shareUrl = "https://sintest.storeer.com/activity_2018/eightHalf_index?productCode=" + recommendDetailGoodsBean.getProductCode() + "&appEntranceType=" +
                    AppConstant.APP_ENTRANCE_ANDROID + "&linkStaffCode=" + mUserConfigManager.getUserId() + "&xd_code=XD0001" + "&orderEntryCode=" + orderEntranceCode + "&productType=" + productType;
        }
        DialogShare2Wechat dialogShare2Wechat = DialogShare2Wechat.getDialogShare2Wechat(recommendDetailGoodsBean);
        dialogShare2Wechat.show(getFragmentManager(), getPageTag());

        dialogShare2Wechat.setOnDialogClickListener(new DialogShare2Wechat.OnDialogClickListener() {
            @Override
            public void onBannerClick(RecBannerBean bean) {
                dialogShare2Wechat.dismissAllowingStateLoss();
                jumpLogic(bean);
            }

            @Override
            public void onShareWechat(RecommendGoodsBean recommendGoodsBean) {

            }

            @Override
            public void onShareCircle(RecommendGoodsBean recommendGoodsBean) {

            }

            @Override
            public void onShareWechat(RecommendDetailGoodsBean recommendGoodsBean) {
                BizUtil.share(mContext, recommendGoodsBean.getProductName(), recommendGoodsBean.getProductName(), shareUrl,
                        recommendGoodsBean.getProductPicUrls().get(0), AppConstant.SHARE_WECHAT);
            }

            @Override
            public void onShareCircle(RecommendDetailGoodsBean recommendGoodsBean) {
                BizUtil.share(mContext, recommendGoodsBean.getProductName(), recommendGoodsBean.getProductDesc(), shareUrl,
                        recommendGoodsBean.getProductPicUrls().get(0), AppConstant.SHARE_WECHAT_CIRCLE);
            }
        });
    }

    private void jumpLogic(RecBannerBean bean) {
        BaseFragment fragment = AdJumpUtil.jumpToDestination(bean.getJumpMode(), bean.getPageSdCode(), bean.getRelCode(), bean.getRelName(), bean.getJumpUrl());
        if (fragment instanceof FragmentRecommendHome) {
            pop();
        } else if (fragment instanceof FragmentVirtualActivity) {
            Intent intent = new Intent(getContext(), ActivityActivityDetail.class);
            Bundle bundle = new Bundle();
            bundle.putString(AppConstant.WEB_URL, fragment.getArguments().getString(AppConstant.WEB_URL));
            bundle.putString(AppConstant.WEB_TITLE, fragment.getArguments().getString(AppConstant.WEB_TITLE));
            intent.putExtras(bundle);
            startActivity(intent);
        } else {
            start(fragment);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {

    }

    @Override
    public void requestError(String error) {

    }

    @Override
    public String getPageTag() {
        return FragmentRecGoodsDetail.class.getCanonicalName();
    }

    private void bindGoodsDetail(RecommendDetailGoodsBean recommendDetailGoodsBean) {
        this.recommendDetailGoodsBean = recommendDetailGoodsBean;
        loadRootFragment(R.id.slidedetail_front, FragmentRecGoodsFront.newInstance(recommendDetailGoodsBean));
//        showGoodsWebview(recommendDetailGoodsBean.getProductCode());
        if (recommendDetailGoodsBean.getTotalStoreSum() == 0) {
            tvGoodsStatus.setBackgroundResource(R.drawable.bg_goods_sale_out);
            tvGoodsStatus.setText("已售空");
            shareFlag = false;
        } else {
            if (recommendDetailGoodsBean.isSecSymbol()) {
                if (recommendDetailGoodsBean.getTotalStoreSum() == 0) {
                    tvGoodsStatus.setBackgroundResource(R.drawable.bg_goods_sale_out);
                    tvGoodsStatus.setText("已售空");
                    shareFlag = false;
                } else {
                    if (recommendDetailGoodsBean.getSecStatus() == AppConstant.GOODS_SEC_NOT_START) {
                        tvGoodsStatus.setBackgroundResource(R.drawable.bg_goods_share_first);
                        tvGoodsStatus.setText("先去分享,秒杀快人一步。");
                        shareFlag = false;
                    } else if (recommendDetailGoodsBean.getSecStatus() == AppConstant.GOODS_SEC_START) {
                        tvGoodsStatus.setBackgroundResource(R.drawable.bg_goods_share_now);
                        tvGoodsStatus.setText("立即分享");
                        shareFlag = true;
                    } else if (recommendDetailGoodsBean.getSecStatus() == AppConstant.GOODS_SEC_END) {
                        tvGoodsStatus.setBackgroundResource(R.drawable.bg_goods_sale_out);
                        tvGoodsStatus.setText("已售空");
                        shareFlag = false;
                    }
                }
            } else {
                tvGoodsStatus.setBackgroundResource(R.drawable.bg_goods_share_now);
                tvGoodsStatus.setText("立即分享");
                shareFlag = true;
            }
        }
    }

    private void trackViewGoods() {
        TraceBean bean = new TraceBean();
        bean.setXdCode("XD0007");
        bean.setYdCode("YD0001");
        if (recommendDetailGoodsBean.isSecSymbol()) {
            bean.setProductType("" + 1);
        } else {
            bean.setProductType("" + 2);
        }
        bean.setProductCode(recommendDetailGoodsBean.getProductCode());
        TraceManager.getTraceManager(mContext).trackViewGoods(bean);
    }

    private void showGoodsWebview(String content) {
        mWebview.loadDataWithBaseURL(null, content, "text/html", "utf-8", null);
        mSlideDetailsLayout.setLock(false);
    }


    private void getRecommendGoodsDetail(String productCode) {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    RecommendDetailGoodsBean recommendDetailGoodsBean = (RecommendDetailGoodsBean) JsonUtil.getObject(response.getReturnContent(), RecommendDetailGoodsBean.class);
                    if (recommendDetailGoodsBean != null) {
                        bindGoodsDetail(recommendDetailGoodsBean);
                        trackViewGoods();
                    }
                }
            }
        };
        ApiMethodGuide.getProductDetail(productCode, new SimpleLbObserver(listener, otherListener), this, FragmentEvent.DESTROY_VIEW);
    }

    public void getProductDetailPic(String productCode) {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    showGoodsWebview(response.getReturnContent().toString());
                }
            }
        };
        ApiMethodGuide.getGoodsPicDetail(productCode, new SimpleLbObserver(listener, otherListener), this, FragmentEvent.DESTROY_VIEW);
    }
}
